<template>
  <el-dialog
    v-model="visible"
    title="远程控制"
    width="600px"
    :before-close="handleClose"
  >
    <div v-loading="loading">
      <el-tabs v-model="activeTab">
        <!-- 治疗控制 -->
        <el-tab-pane label="治疗控制" name="treatment">
          <el-form
            ref="treatmentFormRef"
            :model="treatmentForm"
            :rules="treatmentRules"
            label-width="100px"
          >
            <el-form-item label="治疗模式" prop="mode">
              <el-select v-model="treatmentForm.mode" placeholder="请选择治疗模式">
                <el-option label="模式A" value="mode_a" />
                <el-option label="模式B" value="mode_b" />
                <el-option label="模式C" value="mode_c" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="持续时间" prop="duration">
              <el-slider
                v-model="treatmentForm.duration"
                :min="60"
                :max="3600"
                :step="60"
                show-input
                show-input-controls="false"
              />
              <div class="time-display">{{ formatDuration(treatmentForm.duration) }}</div>
            </el-form-item>
            
            <el-form-item label="电流强度" prop="intensity">
              <el-slider
                v-model="treatmentForm.intensity"
                :min="0.1"
                :max="5"
                :step="0.1"
                show-input
                show-input-controls="false"
              />
              <div class="intensity-display">{{ formatIntensity(treatmentForm.intensity) }}</div>
            </el-form-item>
            
            <el-form-item label="频率" prop="frequency">
              <el-slider
                v-model="treatmentForm.frequency"
                :min="1"
                :max="100"
                :step="1"
                show-input
                show-input-controls="false"
              />
              <div class="frequency-display">{{ formatFrequency(treatmentForm.frequency) }}</div>
            </el-form-item>
            
            <el-form-item>
              <el-button
                type="primary"
                @click="startTreatment"
                :disabled="device.treatment_status === 'running'"
              >
                开始治疗
              </el-button>
              <el-button
                @click="pauseTreatment"
                :disabled="device.treatment_status !== 'running'"
              >
                暂停治疗
              </el-button>
              <el-button
                type="danger"
                @click="stopTreatment"
                :disabled="!device.treatment_status || device.treatment_status === 'completed'"
              >
                停止治疗
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 参数设置 -->
        <el-tab-pane label="参数设置" name="settings">
          <el-form
            ref="settingsFormRef"
            :model="settingsForm"
            label-width="120px"
          >
            <el-form-item label="电极位置">
              <el-select v-model="settingsForm.electrode_position" placeholder="请选择电极位置">
                <el-option label="F3-F4" value="F3-F4" />
                <el-option label="C3-C4" value="C3-C4" />
                <el-option label="P3-P4" value="P3-P4" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="治疗部位">
              <el-select v-model="settingsForm.treatment_area" placeholder="请选择治疗部位">
                <el-option label="前额叶" value="frontal_lobe" />
                <el-option label="顶叶" value="parietal_lobe" />
                <el-option label="颞叶" value="temporal_lobe" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="安全限制">
              <el-switch v-model="settingsForm.safety_limit" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 系统命令 -->
        <el-tab-pane label="系统命令" name="system">
          <div class="system-commands">
            <el-button
              type="warning"
              @click="sendCommand('reboot')"
              block
            >
              重启设备
            </el-button>
            <el-button
              type="warning"
              @click="sendCommand('reset')"
              block
            >
              恢复出厂设置
            </el-button>
            <el-button
              type="warning"
              @click="sendCommand('update_firmware')"
              block
            >
              固件升级
            </el-button>
            <el-button
              type="danger"
              @click="sendCommand('factory_reset')"
              block
            >
              清除所有数据
            </el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { formatDuration, formatIntensity, formatFrequency } from '@/utils/format'

interface Device {
  id: string
  treatment_status: string
  // 其他设备属性
}

interface Props {
  modelValue: boolean
  device: Device
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'command', command: string, params?: any): void
  (e: 'refresh'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(false)
const loading = ref(false)
const activeTab = ref('treatment')

// 表单引用
const treatmentFormRef = ref<FormInstance>()
const settingsFormRef = ref<FormInstance>()

// 治疗控制表单
const treatmentForm = ref({
  mode: 'mode_a',
  duration: 1800, // 30分钟
  intensity: 2.0, // 2.0mA
  frequency: 10   // 10Hz
})

// 参数设置表单
const settingsForm = ref({
  electrode_position: 'F3-F4',
  treatment_area: 'frontal_lobe',
  safety_limit: true
})

// 表单验证规则
const treatmentRules = {
  mode: [
    { required: true, message: '请选择治疗模式', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请选择持续时间', trigger: 'change' }
  ],
  intensity: [
    { required: true, message: '请选择电流强度', trigger: 'change' }
  ],
  frequency: [
    { required: true, message: '请选择频率', trigger: 'change' }
  ]
}

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
})

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
})

const handleClose = () => {
  visible.value = false
}

const startTreatment = async () => {
  if (!treatmentFormRef.value) return
  
  await treatmentFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      emit('command', 'start_treatment', treatmentForm.value)
      handleClose()
    } catch (error) {
      ElMessage.error('开始治疗失败')
      console.error(error)
    }
  })
}

const pauseTreatment = () => {
  emit('command', 'pause_treatment')
  handleClose()
}

const stopTreatment = () => {
  emit('command', 'stop_treatment')
  handleClose()
}

const saveSettings = () => {
  emit('command', 'save_settings', settingsForm.value)
  ElMessage.success('设置已保存')
  handleClose()
}

const sendCommand = (command: string) => {
  emit('command', command)
  handleClose()
}
</script>

<style scoped lang="scss">
.system-commands {
  .el-button {
    margin-bottom: 15px;
  }
}

.time-display,
.intensity-display,
.frequency-display {
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}
</style>